<template>
  <div class="pothole-management">
    <!-- 搜索和添加按钮 -->
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索城市"
        style="width: 150px; margin-right: 10px"
      />
      <!-- 危险程度选择器 -->
      <el-select
        v-model="selectedRisk"
        placeholder="危险程度"
        style="width: 100px; margin-right: 10px"
        clearable
      >
        <el-option label="严重缺陷" value="serious" />
        <el-option label="中等缺陷" value="medium" />
        <el-option label="轻微缺陷" value="slight" />
      </el-select>
      <el-button type="primary" @click="Reset">重置</el-button>

      <el-button type="primary" @click="handleAdd">添加坑洞</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="potholes" border style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="60" label="序号" align="center" />
      <el-table-column prop="risk" label="危险程度" width="120">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.risk)" effect="dark">
            {{ dangerLevelMap[row.risk] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="image" label="照片" width="100" align="center">
        <template #default="{ row }">
          <div class="image-container">
            <el-image
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              style="width: 60px; height: 60px"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="location" label="位置信息">
        <template #default="{ row }">
          <div>经纬度：{{ row.longitude }}, {{ row.latitude }}</div>
          <div>城市：{{ row.city }}</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[2, 5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑坑洞' : '添加坑洞'">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="危险程度" prop="risk">
          <el-radio-group v-model="form.risk">
            <el-radio label="serious">严重缺陷</el-radio>
            <el-radio label="medium">中等缺陷</el-radio>
            <el-radio label="slight">轻微缺陷</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="照片" prop="image">
          <el-upload
            v-model:file-list="form.imageFiles"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-change="handleUploadChange"
            :on-exceed="handleExceed"
            :class="{ 'hide-upload': form.imageFiles.length >= 1 }"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="经度" prop="longitude">
          <el-input v-model.number="form.longitude" type="number" />
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input v-model.number="form.latitude" type="number" />
        </el-form-item>

        <el-form-item label="城市名称" prop="city">
          <el-input v-model="form.city" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getHoleList, updateHole, addHole, deleteHole } from '@/api/hole'

const dangerLevelMap = {
  serious: '严重缺陷',
  medium: '中等缺陷',
  slight: '轻微缺陷',
}

// 响应式数据
const potholes = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
// 更新总条数为过滤后数据长度
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  risk: '',
  imageFiles: [],
  longitude: null,
  latitude: null,
  city: '',
})

// 验证规则
const rules = {
  risk: [{ required: true, message: '请选择危险程度', trigger: 'change' }],
  longitude: [
    { required: true, message: '请输入经度' },
    //必须是数字字符或者数字 自定义校验
    // { validator: (rule, value) => /^-?\d+(\.\d+)?$/.test(value) || '请输入数字' }
  ],
  latitude: [
    { required: true, message: '请输入纬度' },
    { validator: (rule, value) => /^-?\d+(\.\d+)?$/.test(value) || '请输入数字' },
  ],
  city: [{ required: true, message: '请输入城市名称', trigger: 'blur' }],
}
// 添加响应式变量
const selectedRisk = ref('')

const getTagType = (level) => {
  const map = { serious: 'danger', medium: 'warning', slight: 'success' }
  return map[level] || 'info'
}

const handleUploadChange = (file) => {
  // 生成预览 URL
  const previewUrl = URL.createObjectURL(file.raw)

  form.imageFiles = [
    {
      ...file,
      uid: file.uid,
      name: file.name,
      status: file.status,
      url: previewUrl, // 关键：添加预览地址
      raw: file.raw,
    },
  ]
}

const handleExceed = (files) => {
  const newFile = files[0]
  const previewUrl = URL.createObjectURL(newFile)

  form.imageFiles = [
    {
      uid: Date.now(),
      name: newFile.name,
      status: 'ready',
      url: previewUrl, // 关键：添加预览 URL
      raw: newFile,
    },
  ]
}
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, {
    ...row,
    imageFiles: row.image
      ? [
          {
            uid: Date.now(), // 必需字段
            name: 'existing.jpg', // 必需字段
            status: 'success', // 显示上传成功状态
            url: row.image, // 图片预览地址
          },
        ]
      : [],
  })
  dialogVisible.value = true
}

const handleAdd = () => {
  isEdit.value = false
  Object.keys(form).forEach((key) => {
    form[key] = key === 'imageFiles' ? [] : null
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该记录吗？', '提示', { type: 'warning' })
    await deleteHole(row.id)

    await loadData()

    ElMessage.success('删除成功')
  } catch {
    ElMessage.error('删除失败')
  }
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    const formData = ref({
      ...form,
      image: form.imageFiles[0].url,
    })

    //将formData.value.latitude,formData.value.longitude转换为字符串类型
    formData.value.latitude = formData.value.latitude.toString()
    formData.value.longitude = formData.value.longitude.toString()
    let res = null
    if (isEdit.value) {
      res = await updateHole(formData.value)
    } else {
      res = await addHole(formData.value)
    }
    console.log(res)

    if (res.data.code === 0) {
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
      return
    }

    dialogVisible.value = false
    await loadData()
    ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}
const loadData = async () => {
  const res = await getHoleList({
    pageSize: pageSize.value,
    pageNum: currentPage.value,
    city: searchKeyword.value, // 添加搜索参数
    risk: selectedRisk.value, // 添加危险程度筛选参数
  })

  potholes.value = res.data.data.records
  total.value = res.data.data.total // 使用后端返回的总数
}

// 添加搜索和筛选的watch监听
watch([searchKeyword, selectedRisk], () => {
  currentPage.value = 1 // 重置为第一页
  loadData()
})

onMounted(loadData)

const Reset = () => {
  searchKeyword.value = ''
  selectedRisk.value = ''
  currentPage.value = 1
  loadData()
}
</script>

<style scoped>
/* 确保上传组件容器尺寸 */
:deep(.el-upload-list--picture-card) {
  --el-upload-picture-card-size: 148px;
}

/* 隐藏超出限制的上传按钮 */
.hide-upload .el-upload--picture-card {
  display: none;
}
.pothole-management {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.image-container {
  display: flex;
  justify-content: center;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
